<template>
  <div class="bigbox">
    <!-- 列表页面 -->
    <template v-if="showList">
      <!-- 搜索区域 -->
      <div class="topbox">
        <el-form ref="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-form-item label="服务商">
                <FilterSelect2
                  v-model="form.serviceProvider"
                  :optionlist="serviceProviderList"
                  :valuekey="{ name: 'name', value: 'id' }"
                  :clearable="false"
                  @changeSelect="handleServiceProviderChange"
                ></FilterSelect2>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="日期">
                <el-date-picker
                  v-model="value1"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  size="small"
                  style="width: 100%"
                  :clearable="false"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-form-item label="">
                <el-button size="small" @click="handleReset">重置</el-button>
                <el-button size="small" type="primary" @click="handleQuery"
                  >查询</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 主体区域 -->
      <div class="bodybox">
        <TopTitle
          @command="handleCommand"
          @daochu="handleExport"
          @shuaxin="handleRefresh"
        >
          <template #otherbutton>
            <el-button type="primary" size="small" @click="handleAdd">
              新增储能规划
            </el-button>
          </template>
        </TopTitle>
        <!-- 表格区域 -->
        <div class="table">
          <TableColumn
            ref="TableColumn"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :issize="tableSize"
          >
            <el-table-column label="操作" width="180" align="center">
              <template #default="{ row }">
                <div>
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="handleDetail(row)"
                    >详细</el-link
                  >
                  <el-link
                    type="primary"
                    :underline="false"
                    class="link"
                    @click="handleEdit(row)"
                    >编辑</el-link
                  >
                  <el-link
                    type="danger"
                    :underline="false"
                    @click="handleDelete(row)"
                    >删除</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </TableColumn>
        </div>
        <!-- 底部分页 -->
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageObj.pageNo"
            :page-size="pageObj.pageSize"
            @current-change="handlePageChange"
            :total="+totalCount"
          >
          </el-pagination>
        </div>
      </div>
    </template>

    <!-- 表单页面（全屏弹窗） -->
    <EnergyStoragePlanningForm
      v-else
      ref="formRef"
      :initial-data="initialFormData"
      :initial-mode="initialMode"
      @goback="handleGoBack"
    />
  </div>
</template>

<script>
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import TableColumn from '@/components/Table/index.vue'
import TopTitle from '@/components/TopTitle/newtitle.vue'
import EnergyStoragePlanningForm from './form.vue'
import {
  getServiceProviderApi,
  getEnergyStoragePlanningPageApi,
  deleteEnergyStoragePlanApi,
  getEnergyStoragePlanByIdApi
} from '@/api/Microgrid/EnergyStoragePlanning'
import { exportexcel } from '@/utils/excel'
import dayjs from 'dayjs'

export default {
  name: 'EnergyStoragePlanning',
  components: {
    FilterSelect2,
    TableColumn,
    TopTitle,
    EnergyStoragePlanningForm
  },
  data() {
    return {
      showList: true,
      form: {
        serviceProvider: ''
      },
      value1: [],
      serviceProviderList: [],
      manageNo: '', // 保存服务商编码用于接口调用
      tableSize: 'medium',
      pageObj: {
        pageNo: 1,
        pageSize: 15
      },
      tableData: [],
      totalCount: 0,
      initialFormData: null, // 初始表单数据
      initialMode: 'edit', // 初始模式：edit 或 view
      tableConfig: [
        { label: '序号', type: 'index', width: '80', center: 'center' },
        { label: '服务商', prop: 'manageName', center: 'center' },
        { label: '项目名称', prop: 'projectName' },
        { label: '规划日期', prop: 'createDate', center: 'center' },
        {
          label: '建议储能规划容量',
          prop: 'suggestPlanCapacity',
          center: 'center'
        },
        {
          label: '预计投资回报年限',
          prop: 'expectedInvestReturnPeriod',
          center: 'center'
        }
      ]
    }
  },
  async mounted() {
    this.initDateRange()
    // 先获取服务商并设置默认值
    await this.getServiceProviderList()
    // 服务商设置完成后再调用分页接口
    this.getDataList()
  },
  methods: {
    // 初始化日期范围
    initDateRange() {
      const today = dayjs()
      const firstDayOfMonth = today.startOf('month')
      const tomorrow = today.add(1, 'day')
      this.value1 = [
        firstDayOfMonth.format('YYYY-MM-DD'),
        tomorrow.format('YYYY-MM-DD')
      ]
    },
    // 获取服务商列表
    async getServiceProviderList() {
      try {
        const res = await getServiceProviderApi()
        if (res.code === 200 && res.data && res.data.entity) {
          const { manageNo, manageName } = res.data.entity
          this.manageNo = manageNo // 保存服务商编码
          this.serviceProviderList = [
            {
              id: manageNo,
              name: manageName
            }
          ]
          // 默认选中
          this.form.serviceProvider = manageNo
        }
      } catch (error) {
        console.error('获取服务商信息失败:', error)
        this.serviceProviderList = []
      }
    },
    // 获取数据列表
    async getDataList() {
      if (this.$refs.TableColumn) {
        this.$refs.TableColumn.loading = true
      }
      const pageNo = this.pageObj.pageNo
        ? this.pageObj.pageNo - 1
        : this.pageObj.pageNo
      try {
        // 检查必填参数
        if (!this.manageNo) {
          this.$message.warning('请先选择服务商')
          if (this.$refs.TableColumn) {
            this.$refs.TableColumn.loading = false
          }
          return
        }
        if (
          !this.value1 ||
          this.value1.length !== 2 ||
          !this.value1[0] ||
          !this.value1[1]
        ) {
          this.$message.warning('请选择日期范围')
          if (this.$refs.TableColumn) {
            this.$refs.TableColumn.loading = false
          }
          return
        }

        const res = await getEnergyStoragePlanningPageApi({
          manageNo: this.manageNo,
          startDate: this.value1[0],
          endDate: this.value1[1],
          pageNo: pageNo.toString(),
          pageSize: this.pageObj.pageSize.toString()
        })

        if (res.code === 200 && res.data) {
          this.totalCount = res.data.totalCount || 0
          this.tableData = res.data.list || []
        } else {
          this.$message.error(res.message || '获取数据失败')
          this.totalCount = 0
          this.tableData = []
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
        this.totalCount = 0
        this.tableData = []
      } finally {
        if (this.$refs.TableColumn) {
          this.$refs.TableColumn.loading = false
        }
      }
    },
    // 服务商选择变化
    handleServiceProviderChange(value) {
      this.manageNo = value
    },
    // 查询
    handleQuery() {
      this.pageObj.pageNo = 1
      this.getDataList()
    },
    // 重置
    async handleReset() {
      // 重置服务商为默认值
      if (this.serviceProviderList.length > 0) {
        this.form.serviceProvider = this.serviceProviderList[0].id
        this.manageNo = this.serviceProviderList[0].id
      } else {
        // 如果列表为空，重新获取服务商列表
        await this.getServiceProviderList()
      }
      // 重置日期范围
      this.initDateRange()
      // 重置分页
      this.pageObj.pageNo = 1
      // 重新查询
      this.getDataList()
    },
    // 新增
    handleAdd() {
      this.initialFormData = null // 清空初始数据
      this.initialMode = 'edit' // 重置模式
      this.showList = false
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.resetForm()
        }
      })
    },
    // 编辑
    async handleEdit(row) {
      try {
        // 先获取数据
        const res = await getEnergyStoragePlanByIdApi({ id: row.id.toString() })
        if (res && res.code === 200 && res.data) {
          const data = res.data.entity || res.data
          if (data) {
            // 设置初始数据和模式
            this.initialFormData = data
            this.initialMode = 'edit'
            // 数据获取成功后再显示表单
            this.showList = false
            this.$nextTick(() => {
              if (this.$refs.formRef) {
                this.$refs.formRef.loadDataFromInitial(data, 'edit')
              }
            })
          } else {
            this.$message.error('获取数据失败')
          }
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      }
    },
    // 详细
    async handleDetail(row) {
      try {
        // 先获取数据
        const res = await getEnergyStoragePlanByIdApi({ id: row.id.toString() })
        if (res && res.code === 200 && res.data) {
          const data = res.data.entity || res.data
          if (data) {
            // 设置初始数据和模式
            this.initialFormData = data
            this.initialMode = 'view'
            // 数据获取成功后再显示表单
            this.showList = false
            this.$nextTick(() => {
              if (this.$refs.formRef) {
                this.$refs.formRef.loadDataFromInitial(data, 'view')
              }
            })
          } else {
            this.$message.error('获取数据失败')
          }
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      }
    },
    // 返回列表
    handleGoBack() {
      this.showList = true
      this.initialFormData = null // 清空初始数据
      this.initialMode = 'edit' // 重置模式
      this.$nextTick(() => {
        this.getDataList()
      })
    },
    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除这条记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deleteEnergyStoragePlanApi({ id: row.id })
        if (res && res.code === 200) {
          this.$message.success('删除成功')
          this.getDataList()
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败，请稍后重试')
        }
      }
    },
    // 导出
    handleExport() {
      // 检查必填参数
      if (!this.manageNo) {
        this.$message.warning('请先选择服务商')
        return
      }
      if (
        !this.value1 ||
        this.value1.length !== 2 ||
        !this.value1[0] ||
        !this.value1[1]
      ) {
        this.$message.warning('请选择日期范围')
        return
      }

      exportexcel(
        '/mgd-microservice-biz/mgd/energy/storage/plan/export',
        {
          manageNo: this.manageNo,
          startDate: this.value1[0],
          endDate: this.value1[1]
        },
        '储能规划'
      )
    },
    // 刷新
    handleRefresh() {
      this.getDataList()
    },
    // 表格密度
    handleCommand(val) {
      this.tableSize = val
    },
    // 分页变化
    handlePageChange() {
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
.bigbox {
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;

  .topbox {
    height: 80px;
    background-color: #fff;
    margin-bottom: 10px;
    padding: 20px;
  }

  .bodybox {
    margin-top: 10px;
    padding: 20px;
    background-color: #fff;
    height: calc(100% - 90px);

    .table {
      height: calc(100% - 77px);
      margin: 10px 0;

      .link {
        margin: 0 20px;
      }
    }

    .fenye {
      text-align: right;
      margin-top: 10px;
    }
  }
}
</style>
